import { ref, useSSRContext } from 'vue'
import { useUserStore } from '@/common/store'
import { useAddressToCoder } from '@/common/composables/useAddressToCoder'

const { hope_user_info } = useUserStore()
const key = ref(import.meta.env.HOPE_TX_MAP_KEY)
const referer = ref(import.meta.env.HOPE_TX_MAP_APP_NAME)

interface LocationCoder {
  latitude: number
  longitude: number
}

/**
 * 打开腾讯路线规划地图
 * @param targetAddress
 */
export const openTXMapRoutePlan = async (targetAddress: string | undefined, locationCoder?: LocationCoder) => {
  /** 目标地址 */
  const targetLocation = ref({
    latitude: 0,
    longitude: 0,
    address: targetAddress || '北京市海淀区彩和坊路海淀西大街74号',
  })

  /** 用户地址 */
  const userLocation = ref({
    latitude: 0,
    longitude: 0,
    address: hope_user_info?.address,
  })

  // 如果用户传递了经纬度则使用用户传递的
  if (locationCoder) {
    console.log(`locationCoder:${locationCoder.longitude}`)

    userLocation.value.longitude = locationCoder.longitude
    userLocation.value.latitude = locationCoder.latitude
  }
  else {
    // 否则则获取
    /**
     * 用户经纬度
     */
    const userCoder = await useAddressToCoder(userLocation.value.address!) as any
    userLocation.value.longitude = userCoder.lng
    userLocation.value.latitude = userCoder.lat
  }
  console.log('userLocation:', userLocation.value)

  /**
   * 目标经纬度
   */
  const targetCoder = await useAddressToCoder(targetLocation.value.address) as any
  targetLocation.value.longitude = targetCoder.lng
  targetLocation.value.latitude = targetCoder.lat

  console.log(userLocation.value.address)

  /**
   * 起始地址
   */
  const startPoint = JSON.stringify({
    name: userLocation.value.address,
    scale: 18,
    latitude: userLocation.value.latitude,
    longitude: userLocation.value.longitude,
  })

  /**
   * 终点地址
   */
  const endPoint = JSON.stringify({
    name: targetLocation.value.address,
    scale: 18,
    latitude: targetLocation.value.latitude,
    longitude: targetLocation.value.longitude,
  })

  goToPage(`plugin://routePlan/index?key=${key.value}&referer=${referer.value}&endPoint=${endPoint}&startPoint=${startPoint}`)
}

/**
 * 打开腾讯地图选点
 */
export const openTXMapChooseLocation = () => {
  let location

  uni.getLocation({
    type: 'wgs84',
    success(result) {
      const { latitude, longitude } = result

      location = JSON.stringify({
        latitude,
        longitude,
      })
      console.log(location)
      goToPage(`plugin://chooseLocation/index?key=${key.value}&referer=${referer.value}&location=${location}`)
    },
  })
}
